package com.mdp.im.core.subscriber.listener;

import com.mdp.im.core.utils.MQChannelNames;
import com.mdp.im.core.subscriber.MessageSubscriber;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

@Service
public class ImMessageListener implements MessageListener {


	RedisSerializer<String> stringSerializer=RedisSerializer.string();
	
	@Autowired
	StringRedisTemplate redisTemplate;
	
	@Autowired
    MessageSubscriber scbscriber;
	


    private static final Logger logger = LoggerFactory.getLogger(ImMessageListener.class);
	
    /*定时心跳*/
    @Scheduled(cron = "0/10 * * * * *")
    public void timer() {
        redisTemplate.convertAndSend("im_system", "");
        redisTemplate.opsForValue().set("headbea", "1");
    }
	
	
	@Override
	public void onMessage(Message message, byte[] pattern) {
		try {
			// TODO Auto-generated method stub 
			String msg=message.toString();
			logger.debug("消息下行开始----》"+msg);
			//logger.debug(msg);
			//心跳包
			if("".equals(msg)||"\"\"".equals(msg)) {
				return;
			}
			String channelName=stringSerializer.deserialize(pattern);
			if(channelName.startsWith(MQChannelNames.IM_GROUP)) {
				String groupId=channelName.substring(9);
				scbscriber.onGroupMessage(groupId, msg);
			}else if(channelName.startsWith(MQChannelNames.IM_PRICHAT)) {
				scbscriber.onPrichatMessage(msg);
			}else if(channelName.startsWith(MQChannelNames.IM_SYS)) {
				scbscriber.onSysMessage(msg);
			}
		} catch (Exception e) {
			logger.error("",e);
		}finally {
			logger.debug("消息下行结束!!!!!!!!");
		}
		
	}

	 
}
